/*
 * @Description: 线路规划页面
 * @Author: jun.fu
 * @Date: 2019-03-07 17:37:23
 * @Last Modified by:   jun.fu
 * @Last Modified time: 2019-03-07 17:37:23
 */
import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  FlatList,
  RefreshControl
} from 'react-native'
import StartAndEndPosition from '../components/RoutePlan/components/StartAndEndPosition'
import flexStyle from '../configs/flex'
import { px2dp, showToast } from 'rn-xiaobu-utils'
import { iconDefaultColor } from '../configs/skin'
import { getRoutes } from '../components/RoutePlan/api/api'
import RouteInfo from '../components/RoutePlan/components/RouteInfo'
import StationInfo from '../components/RoutePlan/models/StationInfo'
import Loading from '../components/public/loading'
import fontsize from '../configs/fontsize'
import Icon from '../components/public/icon'
import { routePlanPositionCache } from '../components/public/confs/StorageKeys';

export default class RoutePlan extends Component {
  static navigationOptions = {
    header: null
  }

  state = {
    tab: 1, // 1、少换乘<默认>；2、少站点
    list: [],
    refreshing: false,
    startStation: new StationInfo(this.props.navigation.getParam('start')),
    endStation: new StationInfo(this.props.navigation.getParam('end')),
    isLoading: false
  }

  componentDidMount() {
    this.getListData()
  }

  /**
   * 切换查询的方案（少换乘，少站点）
   * @param tab
   */
  changeTab = tab => {
    if (tab !== this.state.tab) {
      this.setState(
        {
          tab
        },
        this.getListData
      )
    }
  }

  /**
   * 获取列表数据
   * @returns {Promise<void>}
   */
  async getListData() {
    this.setState({
      isLoading: true
    })
    try {
      let res = await getRoutes(
        this.state.startStation.lng,
        this.state.startStation.lat,
        this.state.endStation.lng,
        this.state.endStation.lat,
        this.state.tab
      )
      // console.log(res)
      // 数据放置到state中
      this.setState({
        list: res.list
      })
    } catch (e) {
      console.log(e)
    } finally {
      // 结束加载中标签
      this.setState({
        isLoading: false
      })
    }
  }

  /**
   * 下拉刷新，获取列表数据
   * @private
   */
  _onRefresh = () => {
    this.getListData()
  }

  /**
   * 交换起点终点，并重新获取数据
   */
  switchStartAndEnd = () => {
    // let originStartStation = this.state.startStation
    // let orginEndStation = this.state.endStation
    this.setState(
      {
        startStation: this.state.endStation,
        endStation: this.state.startStation
      },
      this.getListData
    )
  }

  /**
   * 更改起点，并重新获取数据
   */
  changeStartStation = () => {
    // 跳转站点查询页
    this.props.navigation.push('SearchDetails', {
      type: 3,
      shouldBack: true,
      needMyPosition: true,
      cacheKey: routePlanPositionCache,
      getInfo: info => {
        // 起点站获取回调
        if (info.id === this.state.endStation.id) {
          showToast('起终点不能相同')
          return
        }
        this.setState(
          {
            startStation: new StationInfo(info)
          },
          this.getListData
        )
      }
    })
  }

  /**
   * 切换终点站，并重新获取数据
   */
  changeEndStation = () => {
    // 跳转站点查询页
    this.props.navigation.push('SearchDetails', {
      type: 3,
      shouldBack: true,
      needMyPosition: true,
      cacheKey: routePlanPositionCache,
      getInfo: info => {
        // 终点站获取回调
        if (info.id === this.state.startStation.id) {
          showToast('起终点不能相同')
          return
        }
        this.setState(
          {
            endStation: new StationInfo(info)
          },
          this.getListData
        )
      }
    })
  }

  /**
   * 返回
   */
  back = () => {
    this.props.navigation.goBack()
  }

  /**
   * 少换乘、少站点tab渲染
   * @returns {*}
   */
  renderTab = () => {
    return (
      <View
        style={[
          flexStyle.flexH,
          {
            marginTop: px2dp(16),
            marginBottom: px2dp(16),
            backgroundColor: '#ffffff'
          }
        ]}
      >
        {/* 少换乘tab */}
        <TouchableOpacity
          style={[
            { flex: 1 },
            flexStyle.flexH,
            flexStyle.flexHc,
            flexStyle.flexVc
          ]}
          onPress={() => {
            this.changeTab(1)
          }}
        >
          <Text
            style={[
              styles.tabText,
              {
                color: this.state.tab === 1 ? iconDefaultColor : null,
                borderBottomWidth: this.state.tab === 1 ? px2dp(6) : 0
              }
            ]}
          >
            少换乘
          </Text>
        </TouchableOpacity>
        {/* 少站点tab */}
        <TouchableOpacity
          style={[
            { flex: 1 },
            flexStyle.flexH,
            flexStyle.flexHc,
            flexStyle.flexVc
          ]}
          onPress={() => {
            this.changeTab(2)
          }}
        >
          <Text
            style={[
              styles.tabText,
              {
                color: this.state.tab === 2 ? iconDefaultColor : null,
                borderBottomWidth: this.state.tab === 2 ? px2dp(6) : 0
              }
            ]}
          >
            少站点
          </Text>
        </TouchableOpacity>
      </View>
    )
  }

  /**
   * 路线信息渲染
   * @param {SimpleRoute} item 路线信息
   * @returns {*}
   * @private
   */
  _renderItem = ({ item, index }) => {
    return <RouteInfo {...item} index={index} />
  }

  /**
   * 列表空数据渲染
   * @returns {*}
   * @private
   */
  _ListEmptyComponent = () => (
    <View style={[flexStyle.flexV, flexStyle.flexVc, { flex: 1 }]}>
      <Image
        source={require('../../assets/img/RoutePlan/route.png')}
        style={styles.emptyImage}
      />
      <Text style={[fontsize.fontsize34, { color: '#C4CDCE' }]}>
        没有适合换乘的路线
      </Text>
    </View>
  )

  render() {
    return (
      <View style={styles.container}>
        {/* 加载中遮罩 */}
        {this.state.isLoading ? <Loading loading={'加载中'} /> : null}
        {/* 标题栏 */}
        <View style={[flexStyle.flexH, { backgroundColor: '#ffffff' }]}>
          {/* 返回键 */}
          <TouchableOpacity
            style={[
              { width: px2dp(106), paddingTop: px2dp(30) },
              flexStyle.flexH,
              flexStyle.flexHc
            ]}
            onPress={this.back}
            activeOpacity={0.6}
          >
            <Icon name={'back'} size={40} />
          </TouchableOpacity>
          {/* 起末站点选择器 */}
          <StartAndEndPosition
            startName={this.state.startStation.name}
            endName={this.state.endStation.name}
            switch={this.switchStartAndEnd}
            changeStartStation={this.changeStartStation}
            changeEndStation={this.changeEndStation}
          />
        </View>
        {/* 路线列表 */}
        <FlatList
          style={{ flex: 1 }}
          data={this.state.list}
          extraData={this.state}
          renderItem={this._renderItem}
          keyExtractor={(item, index) => {
            return index + ''
          }}
          refreshControl={
            <RefreshControl
              refreshing={this.state.refreshing}
              onRefresh={this._onRefresh}
            />
          }
          ListHeaderComponent={this.renderTab}
          ListEmptyComponent={this._ListEmptyComponent}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F2F5F6'
  },
  tabText: {
    height: px2dp(100),
    lineHeight: px2dp(100),
    borderBottomColor: iconDefaultColor
  },
  emptyImage: {
    width: px2dp(480),
    height: px2dp(295),
    marginTop: px2dp(207),
    marginBottom: px2dp(58)
  }
})
